<!-- 学社 - 搜索 -->
<template>
  <view>
    <z-paging-list ref="list" v-model="state.list" :safe-area-inset-bottom="false" @loadData="loadData">
      <template #top>
        <z-navbar title="搜索" />
        <view class="px-4 pt-3">
          <!-- 搜索框 -->
          <u-search shape="square" :show-action="false" clearabled v-model="state.keyword" height="72" bg-color="#fff"
            color="#333" border-color="#F6F6F6" :input-style="searchInputStyle" placeholder-color="#999"
            :placeholder='state.type == "society"?"搜索学社、ID或创建人":"搜索课程"' @search="onSearch" @clear="refresh">
          </u-search>
          <!-- 搜索记录 -->
          <view v-if="state.list.length <= 0 && state.historyList.length > 0" class="mt-3">
            <view class="flex justify-between items-center">
              <view class="c-#333 text-32 font-bold">搜索记录</view>
              <view class="c-#F4AF22 text-28" @click="onClear">清空</view>
            </view>
            <view class="flex flex-col w-full">
              <view v-for="(item, index) in state.historyList" :key="index"
                class="history-item flex items-center pt-3 pb-2">
                <u-image width="30" height="30" src="/static/images/home/ic_history.png" />
                <view class="flex-1 c-#666 text-32 ml-3" @click="onSearch(item)">{{ item }}</view>
                <view class="flex flex-row-reverse h-40">
                  <u-image width="20" height="20" src="/static/images/home/ic_delete.png" @click="onDelete(index)" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>
      <!-- 搜索结果(学社) -->
      <view v-if="state.type == 'society'" class="px-4">
        <view v-if="state.list.length > 0" class="c-#333 text-32 font-bold my-3">相关学社</view>
        <view class="flex flex-col">
          <view v-for="(item, index) in state.list" :key="index" class="history-item flex py-3"
            @click="navigate(item.join_status && item.join_status == 1 ? `/package_society/pages/society/index?tabId=0&club_id=${item.id}` : `/package_society/pages/society/detail?id=${item.id}`)">
            <u-image width="100" height="78" border-radius="12" :src="item.cover_image" />
            <view class="ml-3 flex-1 flex flex-col flex-col-reverse text-single">
              <view class="flex mt-0.5">
                <view class="c-#666 text-24 mr-4">ID:{{ item.clubId }}</view>
                <view class="c-#666 text-24">{{ item.creator?.nickname }}</view>
              </view>
              <view class="c-#666 text-32 text-single" v-html="onLightKeyword(item.club_name, state.keyword)"></view>
            </view>
          </view>
        </view>
      </view>
      <!-- 搜索结果(学社课程) -->
      <view v-if="state.type == 'course'&&state.club_id" class="px-4">
        <view v-for="(item, index) in state.list" :key="index" class="p-4 item flex items-center">
          <u-checkbox :modelValue="isChecked(item)" shape="circle" active-color="#F4AF22"
            @change="checkboxChange($event, item)" />
          <u-image class="mr-2" width="240" height="160" border-radius="12" :src="item.cover_image"></u-image>
          <view class="flex-1 flex flex-col justify-between h-160 text-single">
            <view class="c-#333 text-28 font-bold text-single">{{ item.class_name }}</view>
            <view>
              <view class="c-#B5B5B5 text-24 text-single mb-1">{{ item.desc }}</view>
              <view class="flex">
                <view class="flex-1 flex items-center text-single">
                  <u-image width="32" height="32" shape="circle" :src="item.teacher_image" />
                  <view class="c-#999 text-26 text-single ml-1">{{ item.teacher_name }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 搜索结果(广场课程) -->
      <view v-if="state.type == 'course'&&!state.club_id" class="px-4">
        <view class="pt-4 grid grid-cols-2 gap-3">
        <course-item v-for="(item, index) in state.list" :key="index" :data="item" />
      </view>
      </view>
      <template #bottom>
        <view v-if="state.type == 'course'&&state.club_id" class="h-150 bg-white">
          <u-line class="w-full" color="#eee" :hair-line="false" />
          <view class="btn-submit" @click="onSubmit">确认添加（{{ selectNum }}）</view>
        </view>
      </template>
    </z-paging-list>
  </view>
</template>

<script setup>
import { showModal, navigate } from '@/common/util/uni'
import { getSocietySearch, getCurriculumClaimList, postCurriculumClaim, } from '@/common/http/module/society.js'

const searchInputStyle = {
  borderRadius: "12rpx",
};
const selectNum = computed(() => state.checkedList.length)
const list = ref();
const state = reactive({
  club_id: '',
  keyword: '', // 搜索词
  list: [],
  historyList: [],
  type: '', // 搜索记录
  checkedList: [] // 选中课程
});

// 添加
function onSubmit() {
  const courseIds = state.checkedList.map(v => v.id)
  postCurriculumClaim({
    club_id: state.club_id,
    class_id: courseIds.join(',')
  }).then(() => {
    navigate(`/package_society/pages/society/index?tabId=3&club_id=${state.club_id}`)
  })
}

// 是否已选中
function isChecked(course) {
  const courseIds = state.checkedList.map(v => v.id)
  return courseIds.includes(course.id) ? true : false
}
// 监听checkbox
function checkboxChange(e, course) {
  // 选中添加 未选中移除
  const isInclude = state.checkedList.some(v => v.id == course.id)
  if (!isInclude) {
    state.checkedList.push(course)
  } else {
    state.checkedList = state.checkedList.filter(v => v.id != course.id)
  }
}

// 搜索
function onSearch(searchVal) {
  if (!searchVal) return
  state.keyword = searchVal
  refresh()
  // 缓存
  if (!state.historyList.includes(searchVal)) {
    state.historyList.unshift(searchVal)
    uni.setStorageSync('historyList', JSON.stringify(state.historyList));
  }
}

// 清空
function onClear() {
  showModal({
    title: '提示',
    content: '确认要清空历史记录吗',
    success: function (res) {
      if (res.confirm) {
        // 清空缓存
        state.historyList = []
        uni.removeStorageSync('historyList')
      }
    }
  });
}

// 删除搜索记录
function onDelete(index) {
  showModal({
    title: '提示',
    content: '确认要删除该记录吗',
    success: function (res) {
      if (res.confirm) {
        state.historyList.splice(index, 1)
        uni.removeStorageSync('historyList')
      }
    }
  });
}

// 高亮搜索关键词
function onLightKeyword(title, keyword) {
  const Reg = new RegExp(keyword);
  if (title) {
    const res = title.replace(Reg, `<span style="color: #F4AF22;">${keyword}</span>`);
    return res;
  }
}

// 刷新
function refresh() {
  list.value && list.value.onRefresh()
}

function loadData(page) {
  if (!state.keyword) return
  // 学习成长是已认领课程
  const requestMethod = state.type == 'course' ? getCurriculumClaimList : getSocietySearch
  const params = state.type == 'course' ? { club_id: state.club_id, category_id: '', name: state.keyword, page: page } : { page: page, name: state.keyword }
  requestMethod(params).then(res => {
    list.value.onLoadResult(res.data?.data || [])
  })
}

onLoad((options) => {
  state.type = options.type || ''
  state.club_id = options.club_id || ''
  state.historyList = uni.getStorageSync('historyList') ? JSON.parse(uni.getStorageSync('historyList')) : []
});
</script>

<style lang="scss" scoped>
.history-item {
  border-bottom: 2rpx solid #F5F5F5;
}
</style>
